package com.ruoyi.yijing.service.impl;

import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.CustomerAccountSourePortEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.yijing.domain.CustomerInfo;
import com.ruoyi.yijing.domain.CustomerInfoAccountToken;
import com.ruoyi.yijing.domain.CustomerInfoAccountVo;
import com.ruoyi.yijing.mapper.CustomerInfoAccountTokenMapper;
import com.ruoyi.yijing.service.ICustomerInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.yijing.mapper.CustomerInfoAccountMapper;
import com.ruoyi.yijing.domain.CustomerInfoAccount;
import com.ruoyi.yijing.service.ICustomerInfoAccountService;

import static com.ruoyi.common.constant.CacheConstants.CACHE_PRE;

/**
 * 客户账号Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-02-03
 */
@Service
public class CustomerInfoAccountServiceImpl implements ICustomerInfoAccountService 
{
    @Autowired
    private CustomerInfoAccountMapper customerInfoAccountMapper;

    @Autowired
    private ICustomerInfoService customerInfoService;

    @Autowired
    private CustomerInfoAccountTokenMapper customerInfoAccountTokenMapper;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    public RedisCache redisService;

    //token的过期时间
    private static final Integer EXPIRE_TIME = Constants.TOKEN_EXPIRE * 60;

    /**
     * 查询客户账号
     * 
     * @param customerAccountUid 客户账号主键
     * @return 客户账号
     */
    @Override
    public CustomerInfoAccount selectCustomerInfoAccountByCustomerAccountUid(Long customerAccountUid)
    {
        String key = CACHE_PRE+"CustomerInfoAccount_"+customerAccountUid;
        CustomerInfoAccount tmp = redisService.getCacheObject(key);
        if (tmp == null){
            tmp = customerInfoAccountMapper.selectCustomerInfoAccountByCustomerAccountUid(customerAccountUid);
            if (tmp != null){
                redisService.setCacheObject(key,tmp,5,TimeUnit.MINUTES);
            }
        }
        return tmp;
    }

    /**
     * 查询客户账号列表
     * 
     * @param customerInfoAccount 客户账号
     * @return 客户账号
     */
    @Override
    public List<CustomerInfoAccount> selectCustomerInfoAccountList(CustomerInfoAccount customerInfoAccount)
    {
        return customerInfoAccountMapper.selectCustomerInfoAccountList(customerInfoAccount);
    }

    /**
     * 新增客户账号
     * 
     * @param customerInfoAccount 客户账号
     * @return 结果
     */
    @Override
    public int insertCustomerInfoAccount(CustomerInfoAccount customerInfoAccount)
    {
        return customerInfoAccountMapper.insertCustomerInfoAccount(customerInfoAccount);
    }

    /**
     * 修改客户账号
     * 
     * @param customerInfoAccount 客户账号
     * @return 结果
     */
    @Override
    public int updateCustomerInfoAccount(CustomerInfoAccount customerInfoAccount)
    {
        String key = CACHE_PRE+"CustomerInfoAccount_"+customerInfoAccount.getCustomerAccountUid();
        redisService.deleteObject(key);
        return customerInfoAccountMapper.updateCustomerInfoAccount(customerInfoAccount);
    }

    /**
     * 批量删除客户账号
     * 
     * @param customerAccountUids 需要删除的客户账号主键
     * @return 结果
     */
    @Override
    public int deleteCustomerInfoAccountByCustomerAccountUids(Long[] customerAccountUids)
    {
        return customerInfoAccountMapper.deleteCustomerInfoAccountByCustomerAccountUids(customerAccountUids);
    }

    /**
     * 删除客户账号信息
     * 
     * @param customerAccountUid 客户账号主键
     * @return 结果
     */
    @Override
    public int deleteCustomerInfoAccountByCustomerAccountUid(Long customerAccountUid)
    {
        return customerInfoAccountMapper.deleteCustomerInfoAccountByCustomerAccountUid(customerAccountUid);
    }

    @Override
    public String saveCustomerAccountInfo(CustomerInfoAccountVo customerInfoAccount) {
        DateTime date = DateUtil.date();
        Long accountUid = 0L;
        CustomerInfoAccount accountInfo = new CustomerInfoAccount();
        accountInfo.setAccountName(customerInfoAccount.getAccountName());
        accountInfo.setPlatformUid(customerInfoAccount.getPlatformUid());
        accountInfo = customerInfoAccountMapper.selectCustomerInfoAccount(accountInfo);
        if (accountInfo == null) {

            CustomerInfo ci = null;
            if (StringUtils.isNotEmpty(customerInfoAccount.getNickname()) || StringUtils.isNotEmpty(customerInfoAccount.getHeadimgurl())){
                ci = new CustomerInfo();
                ci.setCustomerName(customerInfoAccount.getNickname());
                ci.setSex(customerInfoAccount.getSex());
                ci.setProvince(customerInfoAccount.getProvince());
                ci.setCity(customerInfoAccount.getCity());
                ci.setProvince(customerInfoAccount.getProvince());
                ci.setHeadImage(customerInfoAccount.getHeadimgurl());
                customerInfoService.insertCustomerInfo(ci);
            }
            accountInfo = new CustomerInfoAccount();
            accountInfo.setAccountName(customerInfoAccount.getAccountName());
            accountInfo.setPlatformUid(customerInfoAccount.getAppId());
            accountInfo.setRegTime(date);
            accountInfo.setAccountStatus("1");
            accountInfo.setCreateDate(date);
            accountInfo.setRegIp(IpUtils.getIpAddr());
            accountInfo.setSourcePort(CustomerAccountSourePortEnum.applet.getKey());
            accountInfo.setOpenId(customerInfoAccount.getOpenId());
            accountInfo.setUnionId(customerInfoAccount.getUnionid());
            if (ci != null){
                accountInfo.setCustomerUid(ci.getCustomerUid());
            }
            customerInfoAccountMapper.insertCustomerInfoAccount(accountInfo);
            accountUid = accountInfo.getCustomerAccountUid();
        } else {
            accountInfo.setUpdateDate(date);

            if (accountInfo.getCustomerUid() == null && (StringUtils.isNotEmpty(customerInfoAccount.getNickname()) || StringUtils.isNotEmpty(customerInfoAccount.getHeadimgurl()))){
                CustomerInfo ci = null;
                ci = new CustomerInfo();
                ci.setCustomerName(customerInfoAccount.getNickname());
                ci.setSex(customerInfoAccount.getSex());
                ci.setProvince(customerInfoAccount.getProvince());
                ci.setCity(customerInfoAccount.getCity());
                ci.setProvince(customerInfoAccount.getProvince());
                ci.setHeadImage(customerInfoAccount.getHeadimgurl());
                customerInfoService.insertCustomerInfo(ci);
                accountInfo.setCustomerUid(ci.getCustomerUid());
            }
            customerInfoAccountMapper.updateCustomerInfoAccount(accountInfo);
            accountUid = accountInfo.getCustomerAccountUid();
        }
        CustomerInfoAccountVo infoAccountVo = new CustomerInfoAccountVo();
        infoAccountVo.setSessionKey(customerInfoAccount.getSessionKey());
        infoAccountVo.setOpenId(accountInfo.getOpenId());
        infoAccountVo.setPlatformUid(accountInfo.getPlatformUid());
        infoAccountVo.setCustomerUid(accountInfo.getCustomerUid());
        String token = rstToken(infoAccountVo, accountUid);
        if (!StringUtils.isEmpty(token)) {
            return token;
        }
        throw new ServiceException("登陆失败，请重试");
    }

    @Override
    public CustomerInfoAccountToken getToken(String token){
        String key = CacheConstants.LOGIN_TOKEN_KEY_CUSTOMER + token;
        CustomerInfoAccountToken rst = redisService.getCacheObject(key);
        if (rst == null){
            rst = customerInfoAccountTokenMapper.selectCustomerInfoAccountToken(token);
            if (rst != null){
                redisService.setCacheObject(key, rst, EXPIRE_TIME, TimeUnit.MINUTES);
            }
        }
        return rst;
    }


    //返回token信息
    public String rstToken(CustomerInfoAccountVo infoAccountVo, Long accountUid) {
            //保存token信息
            logger.info("================未找到CustomerToken,重新生成token========================");
            CustomerInfoAccountToken token = new CustomerInfoAccountToken();
            token.setCustomerAccountUid(accountUid);
            token.setAccessToken(IdUtils.fastUUID());
            token.setClientIp(IpUtils.getIpAddr());
            token.setSecretKey(infoAccountVo.getSessionKey());
            token.setDataStatus("1");
            token.setCustomerUid(infoAccountVo.getCustomerUid());
            token.setPlatformUid(infoAccountVo.getPlatformUid());
            token.setCreateTime(DateUtil.date());
            token.setExpireTime(DateUtils.addSeconds(token.getCreateTime(),EXPIRE_TIME));
            token.setOpenId(infoAccountVo.getOpenId());
            token.setSourcePort(CustomerAccountSourePortEnum.applet.getKey());
            customerInfoAccountTokenMapper.insertCustomerInfoAccountToken(token);
            if (token != null) {
                String key = CacheConstants.LOGIN_TOKEN_KEY_CUSTOMER + token.getAccessToken();
                redisService.setCacheObject(key, token, EXPIRE_TIME, TimeUnit.MINUTES);
                return token.getAccessToken();
            }
        return null;
    }

}
